# pip install Pillow
from django.db import models

class LogistQuestion(models.Model):
    """题库主表：所有题目统一存储，包括选择题与非选择题"""
    QUESTION_TYPES = [
        (1, '选择题'),
        (2, '填空题'),
    ]
    TOPICS = [
        ('逻辑思维题', '逻辑思维题'),
        ('逻辑推理题', '逻辑推理题'),
        ('类比推理题', '类比推理题'),
        ('图形推理题', '图形推理题'),
        ('数学运算', '数学运算'),
        ('阅读理解', '阅读理解'),
    ]

    question_id = models.CharField(max_length=50, unique=True, verbose_name='题目ID')
    stem = models.TextField(verbose_name='题干内容')
    stem_image = models.ImageField(upload_to='question_images/', blank=True, null=True, verbose_name='题干图片')
    question_type = models.PositiveSmallIntegerField(
        choices=QUESTION_TYPES, verbose_name='题目类型'
    )
    topic = models.CharField(
        max_length=20, choices=TOPICS, verbose_name='题目主题'
    )
    score = models.IntegerField(verbose_name='题目分值')
    answer = models.CharField(max_length=100, blank=True, null=True, verbose_name='答案')
    suggested_time = models.IntegerField(
        blank=True, null=True, verbose_name='建议时长'
    )

    def __str__(self):
        return f"[{self.question_id}] ({self.get_question_type_display()}) {self.stem[:30]}..."

class ChoiceOption(models.Model):
    """存储选择题选项"""
    question = models.ForeignKey(
        LogistQuestion, on_delete=models.CASCADE,
        related_name='options', limit_choices_to={'question_type': 1}
    )
    label = models.CharField(
        max_length=1, choices=[('A','A'),('B','B'),('C','C'),('D','D')], verbose_name='选项标签'
    )
    content = models.TextField(verbose_name='选项内容', blank=True, null=True) # 允许选项内容为空（例如，选项纯图片）
    # 用于存储选项中的图片，可以为空
    option_image = models.ImageField(upload_to='option_images/', blank=True, null=True, verbose_name='选项图片')


    class Meta:
        unique_together = ('question', 'label')

    def __str__(self):
        return f"{self.question.question_id}-{self.label}: {self.content}"

class ExamSession(models.Model):
    """考试会话"""
    session_id = models.CharField(max_length=50, unique=True, verbose_name='会话ID')
    created_at = models.DateTimeField(auto_now_add=True, verbose_name='创建时间')
    total_score = models.IntegerField(default=0, verbose_name='总分')
    is_completed = models.BooleanField(default=False, verbose_name='是否完成')

    def calculate_total_score(self):
        """计算总分"""
        answers = self.answers.all()
        total = sum(answer.score_earned for answer in answers)
        self.total_score = total
        self.save()
        return total

    def __str__(self):
        return f"考试会话 {self.session_id} - 总分: {self.total_score}"

class ExamAnswer(models.Model):
    """答题记录"""
    session = models.ForeignKey(
        ExamSession,
        on_delete=models.CASCADE,
        related_name='answers',
        verbose_name='考试会话'
    )
    question = models.ForeignKey(
        LogistQuestion,
        on_delete=models.CASCADE,
        related_name='answers',
        verbose_name='题目'
    )
    user_answer = models.CharField(max_length=100, verbose_name='用户答案')
    is_correct = models.BooleanField(default=False, verbose_name='是否正确')
    score_earned = models.IntegerField(default=0, verbose_name='获得分数')
    answered_at = models.DateTimeField(auto_now_add=True, verbose_name='答题时间')

    def check_answer(self):
        """检查答案并计算得分"""
        self.is_correct = self.user_answer.strip().upper() == self.question.answer.strip().upper()
        self.score_earned = self.question.score if self.is_correct else 0
        self.save()
        return self.is_correct

    class Meta:
        unique_together = ('session', 'question')

    def __str__(self):
        return f"{self.session.session_id} - {self.question.question_id} - {'正确' if self.is_correct else '错误'}"